# -*- coding:utf-8 -*-
from flask import render_template,redirect,request,Response,flash
from . import main
import json,commands
from flask_login import current_user, login_required
import datetime
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

@login_required
@main.route('/')
def index():
    '''
    @note: 当前cbt服务器时间
    '''
    if not current_user.is_authenticated: # 登录成败判断
        return redirect('auth/login')
    else:
        current_tiem = commands.getoutput("date +%F\ %T")
    return render_template('dashboard.html',current_tiem=current_tiem)



@login_required
@main.route('/settime/', methods=['GET', 'POST'])
def settime():
    '''
    @note: cbt服务器时间设定
    '''
    if request.method == 'POST':
        data = request.get_json()['time']
        print data
        try:
            commands.getoutput("date -s '%s'" % data)
            return Response(json.dumps({'result':True,"message":u'设置成功'}), mimetype='application/json')
        except Exception,e:
            return Response(json.dumps({'result': True, "message": u'设置失败。{0}'.format(e)}), mimetype='application/json')
    else:
        return redirect(index)

@login_required
@main.route('/clean_cache/', methods=['GET', 'POST'])
def clean_cache():
    '''
    @note: cbt服务器缓存清理
    '''
    if request.method == 'POST':
        print request.method
        try:
            res = commands.getoutput("/bin/bash /root/clean_cache.sh && /bin/bash /root/clean_cache_gm.sh")
            return Response(json.dumps({'result': True, "message":u'清理缓存成功...\n' + res}))
        except Exception,e:
            return Response(json.dumps({'result': False, "message": u'清理缓存失败...{0}'.format(e)}))
    else:
        return render_template('clean_cache.html')

@login_required
@main.route('/import_data/', methods=['GET', 'POST'])
def import_data():
    '''
    @note: 数据导入导出(jptest-->jpcbt)
    '''
    if request.method == 'POST':
        content = request.form['contenet']
        if request.form['contenet'] == '':
            flash(u'请填写表名称【不能为空】','danger')
            return render_template('import_data.html')
        try:
            # 正式

            # 测试
            data = 'xxxxx'

            flash(u'导入完毕!','success')
            return render_template('import_data.html' ,data=data)
        except Exception,e:
            flash(u'导入失败!{0}'.format(e),'success')
            return render_template('import_data.html' ,data=data)
    return render_template('import_data.html')

@login_required
@main.route('/hot_resorce/', methods=['GET', 'POST'])
def hot_resorce():
    '''
    @note: cbt热更
    '''
    if request.method == 'POST':
        try:
            # 正式
            #data = commands.getoutput("/bin/bash /root/cbt_update_jp_hot.sh")

            # 测试
            data = commands.getoutput("ifconfig")

            flash(u'热更完毕,请复制NewVersion到文本框中！','success')
            return render_template('update_cbt_resouce.html' ,data=data)
        except Exception,e:
            return Response(json.dumps({'result': False, "message": u'热更失败...{0}'.format(e)}))

    return render_template('update_cbt_resouce.html')

@login_required
@main.route('/change_resource/', methods=['GET', 'POST'])
def change_resource():
    '''
    @note: cbt热更版本号替换
    '''
    if request.method == 'POST':
        try:
            content = request.form['contenet']
            if len(content) == 0:
                flash(u'请复制正确的的热更版本号【错误信息: 不能为空! 】','danger')
                return render_template('update_cbt_resouce.html')
            # 正式
            #data = commands.getoutput("ssh jp-cbt 'sh /root/change_resversion.sh.sh %s'" % int(content))

            flash(u'热更版本替换成功  ---  【%s】' % int(content) ,'success')
            return render_template('update_cbt_resouce.html')
        except Exception,e:
            flash(u'热更版本替换失败【错误信息: {0} --- 填入内容必须为整数，字符无效！】'.format(e),'danger')
            return render_template('update_cbt_resouce.html')
    return render_template('update_cbt_resouce.html')

@login_required
@main.route('/update_cbtcode/', methods=['GET', 'POST'])
def update_cbtcode():
    '''
    @note: cbt服务器缓存清理
    '''
    if request.method == 'POST':
        try:
            # 正式
            res = commands.getoutput("/root/update.sh")

            #测试
            #res =  commands.getoutput("date")

            return Response(json.dumps({'result': True, "message":u'CBT代码更新成功...\n' + str(res)}))
        except Exception,e:
            return Response(json.dumps({'result': False, "message": u'CBT代码更新失败...{0}'.format(e)}))
    else:
        return render_template('update_cbtcode.html')
@login_required
@main.route('/re_current/', methods=['GET', 'POST'])
def re_current():
    '''
    @note: cbt服务器时间设定为当前
    '''
    if request.method == "POST":
        import time
        try:
            res = commands.getoutput("ntpdate cn.pool.ntp.org")
            return Response(json.dumps({'result':True, 'message':u'设置为当前时间成功\n' + res}))
        except Exception,e:
            return Response(json.dumps({'result':False, 'message':u'设置为当前时间失败'}))
    else:
        pass


@login_required
@main.route('/addallowip/', methods=['GET', 'POST'])
def addallowip():
    '''
    @note: 维护白名单IP添加
    '''
    if request.method == 'POST':
        content = request.form['addip'].encode('utf8')
        if len(content) == 0:
            flash(u'IP: 不能为空! ','danger')
            return render_template('add_allowip.html')
        try:
            res = commands.getoutput("/bin/bash /root/add_allowlist.sh {0}".format(content))
            print res
            flash(u'IP:添加完毕，手动刷新页面！','success')
            return render_template('add_allowip.html')
        except Exception,e:
            flash(u'IP:添加失败,请联系管理员!\n {0}'.format(e),'danger')
            return render_template('add_allowip.html')
    else:
        res = commands.getoutput("cat /data/warship/config/cbt.jianniang.com/ipList.php")
        return render_template('add_allowip.html',data=res)

@login_required
@main.route('/registerswitch/', methods=['GET', 'POST'])
def registerswitch():
    '''
    @note: 维护白名单IP添加
    '''
    res = commands.getoutput("/bin/bash /root/switch_register.sh check")
    if request.method == 'POST':
        #return Response(json.dumps({'result': True, "message": u'开启成功！...'}))
        action = request.args.get('result', '')
        if action == 'open':
            print action
            res = commands.getoutput("/bin/bash /root/switch_register.sh close")
            return Response(json.dumps({'result': True, "message": u'开启注册功能成功！...'}))
        elif action == 'close':
            print action
            res = commands.getoutput("/bin/bash /root/switch_register.sh open")
            
            return Response(json.dumps({'result': True, "message": u'关闭注册功能成功！...'}))
        else:
            pass
    print res
    if str(res) == 'close':
        result = '已关闭注册功能'

        return render_template('reigster_switch.html',result=result)
    else:
        result = '已开启注册功能'
        return render_template('reigster_switch.html',result=result)


@login_required
@main.route('/addallowuid/', methods=['GET', 'POST'])
def addallowuid():
    '''
    @note: UID白名单
    '''
    if request.method == 'POST':
        content = request.form['addip'].encode('utf8')
        if len(content) == 0:
            flash(u'UID不能为空! ','danger')
            return render_template('add_allowuid.html')
        try:
            res = commands.getoutput("/bin/bash /root/add_allowuid.sh {0}".format(content))
            print res
            flash(u'UID添加完毕，手动刷新页面！','success')
            return render_template('add_allowuid.html')
        except Exception,e:
            flash(u'UID添加失败,请联系管理员!\n {0}'.format(e),'danger')
            return render_template('add_allowuid.html')
    else:
        res = commands.getoutput("cat /data/warship/config/cbt.jianniang.com/uidList.php")
        return render_template('add_allowuid.html',data=res)
